<template>
    <el-button type="primary" @click="openAddDialog">新增工序</el-button>
    <!-- 高级查询按钮 -->
    <el-button style="float: right;"  type="primary" @click="openAdvancedSearch">
      <el-icon><Search /></el-icon>高级查询
    </el-button>
    <!-- 高级查询弹窗 -->
    <el-dialog title="高级查询" v-model="advancedSearchVisible" width="600px">
  <el-form :model="searchForm" label-width="100px">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序编码">
          <el-input v-model="searchForm.ProcessCode" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="工序名称">
          <el-input v-model="searchForm.ProcessName" placeholder="请输入" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序分类">
          <el-select v-model="searchForm.CategoryId" placeholder="请选择工序分类名称">
            <el-option v-for="item in categoryOptions"  :label="item.categoryName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="负责人">
          <el-select v-model="searchForm.PersonId" placeholder="请选择负责人">
            <el-option v-for="item in accountNames"  :label="item.accountName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="所属部门">
            <el-select v-model="searchForm.DepartmentId" placeholder="请选择所属部门">
                <el-option v-for="item in departments"  :label="item.departmentName" :value="item.id" />
            </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态">
          <el-select v-model="searchForm.IsActive" placeholder="请选择状态">
            <el-option label="启用" value="true" />
            <el-option label="禁用" value="false" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <template #footer>
    <el-button @click="resetForm">清空</el-button>
    <el-button type="primary" @click="handleSearch">查询</el-button>
    <el-button @click="advancedSearchVisible = false">关闭</el-button>
  </template>
    </el-dialog>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="processCode" label="工序编码" />
      <el-table-column prop="processName" label="工序名称" />
      <el-table-column prop="categoryName" label="工序分类" />
      <el-table-column prop="personName" label="负责人" />
      <el-table-column prop="departmentName" label="所属部门" />
      <el-table-column prop="isActive" label="状态">
        <template #default="scoped">
          <el-tag :type="scoped.row.isActive ? 'success' : 'danger'">{{ scoped.row.isActive ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="remarks" label="备注" />
        <el-table-column  label="操作" >
            <template #default="scope">
                <el-button type="success" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteRow(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 新增弹窗 -->
<el-dialog title="新增工序" v-model="addDialogVisible" width="600px">
  <el-form :model="addForm" label-width="100px" :rules="addRules" ref="addFormRef">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序编码" prop="processCode">
          <el-input v-model="addForm.processCode" placeholder="请输入工序编码" />
          <el-checkbox v-model="autoGenerateCode" @change="handleAutoGenerateCode">系统编号</el-checkbox>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="addForm.processName" placeholder="请输入工序名称" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序分类" prop="categoryId">
          <el-select v-model="addForm.categoryId" placeholder="请选择工序分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="负责人" prop="personId">
          <el-select v-model="addForm.personId" placeholder="请选择负责人">
            <el-option
              v-for="item in accountNames"
              :key="item.id"
              :label="item.accountName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="addForm.departmentId" placeholder="请选择所属部门">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.departmentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态" prop="isActive">
          <el-checkbox v-model="addForm.isActive">启用</el-checkbox>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="备注" prop="remarks">
      <el-input v-model="addForm.remarks" type="textarea" placeholder="请输入备注" />
    </el-form-item>
  </el-form>

  <template #footer>
    <el-button @click="addDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitAddForm">确定</el-button>
  </template>
</el-dialog>
<!-- 编辑弹窗 -->
<el-dialog title="编辑工序" v-model="editDialogVisible" width="600px">
  <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序编码" prop="processCode">
          <el-input v-model="editForm.processCode" placeholder="请输入工序编码" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="editForm.processName" placeholder="请输入工序名称" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="工序分类" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择工序分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="负责人" prop="personId">
          <el-select v-model="editForm.personId" placeholder="请选择负责人">
            <el-option
              v-for="item in accountNames"
              :key="item.id"
              :label="item.accountName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="editForm.departmentId" placeholder="请选择所属部门">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.departmentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态" prop="isActive">
          <el-checkbox v-model="editForm.isActive">启用</el-checkbox>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="备注" prop="remarks">
      <el-input v-model="editForm.remarks" type="textarea" placeholder="请输入备注" />
    </el-form-item>
  </el-form>

  <template #footer>
    <el-button @click="editDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitEditForm">确定</el-button>
  </template>
</el-dialog>
<!-- 分页 -->
   <div style="margin-top: 20px;">
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[10, 15, 20, 25]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.TotalCount"
    />
   </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref, watch } from 'vue';


const deleteRow = (id: number) => {
  ElMessageBox.confirm('确定要删除该工序吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`api/ProcessManagement/DeleteProcessManagements`,{params:{Id:id}})
      .then(() => {
        ElMessage.success('删除成功');
        getTableData();
      })
      .catch(() => {
        ElMessage.error('删除失败');
      });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 编辑弹窗控制
const editDialogVisible = ref(false);

// 编辑表单数据
const editForm = ref({
  id: null,
  processCode: '',
  processName: '',
  categoryId: null,
  personId: null,
  departmentId: null,
  isActive: true,
  remarks: ''
});
// 打开编辑弹窗
const openEditDialog = (row: any) => {
  editDialogVisible.value = true;
  // 复制当前行数据到编辑表单
  editForm.value = { ...row };
};
// 提交编辑表单
const submitEditForm = () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate((valid: boolean) => {
    if (valid) {
      axios.put('/api/ProcessManagement/UpdateProcessManagements', {
        id: editForm.value.id,
        processCode: editForm.value.processCode,
        processName: editForm.value.processName,
        categoryId: editForm.value.categoryId,
        categoryName: categoryOptions.value.find(c => c.id === editForm.value.categoryId)?.categoryName || '',
        personId: editForm.value.personId,
        personName: accountNames.value.find(p => p.id === editForm.value.personId)?.accountName || '',
        departmentId: editForm.value.departmentId,
        departmentName: departments.value.find(d => d.id === editForm.value.departmentId)?.departmentName || '',
        isActive: editForm.value.isActive,
        remarks: editForm.value.remarks
      }).then(() => {
        ElMessage.success('编辑成功');
        editDialogVisible.value = false;
        getTableData(); // 刷新表格
      }).catch(() => {
        ElMessage.error('编辑失败');
      });
    }
  });
};

// 编辑表单校验规则
const editRules = ref({
  processCode: [{ required: true, message: '请输入工序编码', trigger: 'blur' }],
  processName: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择工序分类', trigger: 'change' }],
  personId: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }]
});

// 编辑表单ref
const editFormRef = ref<FormInstance>();

// 新增弹窗控制
const addDialogVisible = ref(false);
const autoGenerateCode = ref(false);

// 表单数据
const addForm = ref({
  processCode: '',
  processName: '',
  categoryId: null,
  personId: null,
  departmentId: null,
  isActive: true,
  remarks: ''
});
// 表单校验规则
const addRules = ref({
  processCode: [{ required: true, message: '请输入工序编码', trigger: 'blur' }],
  processName: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择工序分类', trigger: 'change' }],
  personId: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }]
});


// 工序分类下拉选项（可从接口获取）
const categoryOptions = ref([
  {
    id:null,
    categoryName:''
  }
]);
// 获取分类数据
const fetchCategories = () => {
  axios.get('/api/ProcessCategory/GetProcessCategorys')
    .then(res => {
      categoryOptions.value = res.data.totalPage;
    });
};
//负责人数据源
const accountNames=ref([{
    id:null,
    accountName:''
}])
// 获取负责人数据
const fetchPersons = () => {
  axios.get('/api/Accounts/ClientGet')
    .then(res => {
      accountNames.value = res.data.totalPage;
    });
};

const departments=ref([{
    id:null,
    departmentName:''
}])

// 获取部门数据
const fetchDepartments = () => {
  axios.get('/api/Accounts/GetDepartments')
    .then(res => {
      departments.value = res.data.data;
    });
};
// 自动生成编码
const handleAutoGenerateCode = () => {
  if (autoGenerateCode.value) {
    // 示例：生成类似 SCDH20250905171045618295 的格式
    const now = new Date();
    const code = `SCDH${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
    addForm.value.processCode = code;
  }
};
// 新增表单ref
import type { FormInstance } from 'element-plus';
const addFormRef = ref<FormInstance>();

// 提交新增表单
const submitAddForm = () => {
    if (!addFormRef.value) return;
    addFormRef.value.validate((valid: boolean) => {
        if (valid) {
            axios.post('/api/ProcessManagement/CreateProcessManagements', {
                processCode: addForm.value.processCode,
                processName: addForm.value.processName,
                categoryId: addForm.value.categoryId,
                categoryName: categoryOptions.value.find(c => c.id === addForm.value.categoryId)?.categoryName || '',
                personId: addForm.value.personId,
                personName: accountNames.value.find(p => p.id === addForm.value.personId)?.accountName || '',
                departmentId: addForm.value.departmentId,
                departmentName: departments.value.find(d => d.id === addForm.value.departmentId)?.departmentName || '',
                isActive: addForm.value.isActive,
                remarks: addForm.value.remarks
            }).then(() => {
                ElMessage.success('新增成功');
                addDialogVisible.value = false;
                getTableData(); // 刷新表格
            }).catch(() => {
                ElMessage.error('新增失败');
            });
        }
    });
};

// 打开新增弹窗
const openAddDialog = () => {
  addDialogVisible.value = true;
  // 重置表单
  addForm.value = {
    processCode: '',
    processName: '',
    categoryId: null,
    personId: null,
    departmentId: null,
    isActive: true,
    remarks: ''
  };
  autoGenerateCode.value = false;
};


// 控制弹窗显示隐藏
const advancedSearchVisible = ref(false);

// 查询表单数据
const searchForm = ref({
  ProcessCode: '',
  ProcessName: '',
  CategoryId: null,
  PersonId: '',
  DepartmentId: '',
  IsActive: null
});



// 打开高级查询弹窗
const openAdvancedSearch = () => {
  advancedSearchVisible.value = true;
};

// 清空表单
const resetForm = () => {
    searchForm.value.ProcessCode = '';
  searchForm.value.ProcessName = '';
  searchForm.value.CategoryId = null;
  searchForm.value.PersonId = '';
  searchForm.value.DepartmentId = '';
  searchForm.value.IsActive = null;
};

// 执行查询
const handleSearch = () => {
  // 将表单数据赋值到 page 对象中
  Object.assign(page.value, searchForm.value);
  getTableData(); // 调用获取数据的方法
  advancedSearchVisible.value = false; // 关闭弹窗
};

const tableData=ref([{
      "id": null,
      "processCode": "",
      "processName": "",
      "categoryId": null,
      "categoryName": "",
      "personId": null,
      "personName": "",
      "departmentId": null,
      "departmentName": "",
      "isActive": null,
      "remarks": ""
}])
const page = ref({
  ProcessCode: '',
  ProcessName: '',
  CategoryId: null,
  PersonId: null,
  DepartmentId: null,
  IsActive: null,
  PageIndex: 1,
  PageSize: 10,
  TotalCount: 0
});
const getTableData=()=>{
    axios.get("/api/ProcessManagement/GetProcessManagements",{params:page.value}).then((res)=>{
        tableData.value=res.data.totalPage

        page.value.TotalCount=res.data.totalcount
    })
}
watch(page.value, () => {
    getTableData()
})

onMounted(()=>{
    getTableData()
    fetchCategories();
  fetchPersons();
  fetchDepartments();
  getTableData();
})

</script>

